import {
  chooseImage,
  uploadFile,
  compressImage,
  showToast,
  showLoading,
  hideLoading
} from '@tarojs/taro';
import { CacheCookies } from '../constant/cache';
import { getCache } from './utils';
import { proxy } from '../constant/config';

const upload = ({ count = 1, name = 'imgFile' }) => {
  return new Promise((resolve, reject) => {
    chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      count: count,
      // @ts-ignore
      success: function(res) {
        compressImage({
          src: res.tempFilePaths[0],
          quality: 80 // 压缩质量
        })
          .then(({ tempFilePath }) => {
            // 成功将图片上传到服务器
            showLoading({ title: '操作中' });
            uploadFile({
              url: proxy + '/file-ajaxUpload.json',
              filePath: tempFilePath,
              name,
              header: {
                cookie: getCache(CacheCookies)
              },
              formData: {
                dir: 'image'
              },
              success({ statusCode, ...rest }) {
                if (statusCode === 200) {
                  const { error, url, message } = JSON.parse(rest.data || '{}');
                  if (error === 0) {
                    resolve(proxy + url);
                    showToast({ title: '上传成功' });
                  } else {
                    showToast({ title: '上传失败', icon: 'none' });
                    reject(message || '上传错误');
                  }
                } else {
                  showToast({ title: '上传失败', icon: 'none' });
                  reject('上传错误');
                }
              },
              fail(error) {
                console.log(error);
                showToast({ title: '上传失败', icon: 'none' });
                reject('上传错误');
              }
            });
          })
          .catch((error) => {
            console.log(error);
            showToast({ title: '上传失败', icon: 'none' });
            reject('上传错误');
          });
      }
    });
  });
};

export default upload;
